package io

import (
	"io"

	"gitee.com/yrwy/msgo/pkg/errors"
)

func Writes[E io.Writer](ws []E, p []byte) (int, error) {
	n := 0
	errs := make(errors.Errors[int])
	for i, w := range ws {
		m, err := w.Write(p)
		if err != nil {
			errs[i] = err
		}
		if n < m {
			n = m
		}
	}
	if len(errs) > 0 {
		return n, errs
	}
	return n, nil
}

func Closes[E io.Closer](cs []E) error {
	errs := make(errors.Errors[int])
	for i, c := range cs {
		err := c.Close()
		if err != nil {
			errs[i] = err
		}
	}
	if len(errs) > 0 {
		return errs
	}
	return nil
}

type Writers []io.Writer

func (x Writers) Write(p []byte) (int, error) {
	return Writes(x, p)
}

type Closers []io.Closer

func (x Closers) Close() error {
	return Closes(x)
}

type WriteClosers []io.WriteCloser

func (x WriteClosers) Write(p []byte) (int, error) {
	return Writes(x, p)
}

func (x WriteClosers) Close() error {
	return Closes(x)
}

func (x WriteClosers) WriteString(s string) (int, error) {
	return Writes(x, []byte(s))
}

func (x WriteClosers) WriteByte(c byte) error {
	_, err := Writes(x, []byte{c})
	return err
}
